package net.towee.server.ftp.files;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import net.towee.model.account.AccountGroup;
import net.towee.model.repo.DocumentNode;
import net.towee.model.repo.NodeData;
import net.towee.model.repo.TreeNode;
import net.towee.server.persistence.AttachmentStore;
import net.towee.server.persistence.DiscussionStore;
import net.towee.server.persistence.DocumentStore;

import org.apache.ftpserver.ftplet.FtpFile;

/**
 * Represent root tree of some group
 * 
 * @author c58
 */
public class TreeNodeFtpFile extends AbstractFtpFile {
	private final AccountGroup group;
	private final DocumentStore docStore;
	private final AttachmentStore attStore;
	private final DiscussionStore discStore;
	private TreeNode node;
	
	public TreeNodeFtpFile(TreeNode node, AccountGroup g, DocumentStore docStore, AttachmentStore attStore,
			DiscussionStore discStore) {
		super( (node != null) ? node.getName() 
							  : g.getGroupIdentity().getAlias(),
							  
			   true, 0, g.getGroupIdentity().getAlias(), "", FtpFileType.TREE_NODE,
			   
			   (node != null) ? "/"+g.getGroupIdentity().getAlias() + node.getPath() + "/" +node.getName() 
					          : "/"+g.getGroupIdentity().getAlias() );
		
		this.group = g;
		this.docStore = docStore;
		this.attStore = attStore;
		this.discStore = discStore;
		this.node = node;
	}

	@Override
	public long getLastModified() {
		return 0;
	}

	@Override
	public List<FtpFile> listFiles() {
		// Get root tree of group 
		List<NodeData> nodes = (node == null) ? docStore.getRootTree( group.getGroupIdentity().getId() )
											  : docStore.getSubTree( node.getGroupId(), node.getId());
		
		// Create empty list for files
		List<FtpFile> files = new ArrayList<FtpFile>();
		
		// Create list of files
		for( NodeData node : nodes ){
			if( node instanceof TreeNode )
				files.add( new TreeNodeFtpFile((TreeNode)node, group, docStore, attStore, discStore) );
			else
				files.add( new DocumentNodeFtpFile((DocumentNode)node, group, docStore, attStore, discStore) );
		}
		
		return files;
	}

	@Override
	public OutputStream createOutputStream(long offset) throws IOException {
		return null;
	}

	@Override
	public InputStream createInputStream(long offset) throws IOException {
		return null;
	}

}
